package com.ruoyi.leave.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.obs.services.internal.ServiceException;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.CommonResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.Arith;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.leave.domain.WorkflowWaterPlan;
import com.ruoyi.leave.mapper.WorkflowWaterPlanMapper;
import com.ruoyi.leave.service.IWorkflowWaterPlanService;
import com.ruoyi.leave.util.WorkFlowCache;
import com.ruoyi.leave.util.WorkFlowConstants;
import com.ruoyi.manage.domain.*;
import com.ruoyi.manage.domain.dto.*;
import com.ruoyi.manage.service.*;
import com.ruoyi.system.service.ISysDeptService;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.common.constant.CommonResult.EXAMINE_TYPE.BESUBMITTED;
import static com.ruoyi.common.constant.CommonResult.EXAMINE_TYPE.NO_PASS;
import static com.ruoyi.common.constant.CommonResult.ZERO;

/**
 * 用水申请Service业务层处理
 *
 * @author ruoyi
 * @date 2023-12-22
 */
@Service
public class WorkflowWaterPlanServiceImpl implements IWorkflowWaterPlanService {
    private static final Logger log = LoggerFactory.getLogger(WorkflowWaterPlanServiceImpl.class);
    @Autowired
    private WorkflowWaterPlanMapper workflowWaterPlanMapper;
    @Autowired
    private WorkFlowCache workFlowCache;

    @Autowired
    private ProcessRuntime processRuntime;

    @Autowired
    private TaskService taskService;

    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private HistoryService historyService;

    @Autowired
    private ISwWaterPlanService waterPlanService;

    @Autowired
    private IBtSwUnitService btSwUnitService;

    @Autowired
    private IBtFlowHistoryService btFlowHistoryService;


    @Autowired
    private ISwWaterPlanMonthlyService swWaterPlanMonthlyService;
    @Resource
    private DynamicJumpService dynamicJumpService;

    @Autowired
    private ISwWaterPlanAnnualService swWaterPlanAnnualService;

    @Autowired
    private ISwWaterPlanDetailService swWaterPlanDetailService;

    @Autowired
    private ISwWaterPlanService swWaterPlanService;

    @Autowired
    private IBsSwQuotaIndustryService swQuotaIndustryService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private ISwWaterPlanAgricultureDetailService swWaterPlanAgricultureDetailService;

    /**
     * 查询用水申请
     *
     * @param id 用水申请ID
     * @return 用水申请
     */
    @Override
    public WorkflowWaterPlan selectWorkflowWaterPlanById(String id) {
        return workflowWaterPlanMapper.selectWorkflowWaterPlanById(id);
    }

    /**
     * 查询用水申请列表
     *
     * @param workflowWaterPlan 用水申请
     * @return 用水申请
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "wwp")
    public List<WorkflowWaterPlan> selectWorkflowWaterPlanList(WorkflowWaterPlan workflowWaterPlan) {
        List<WorkflowWaterPlan> workflowWaterPlans = workflowWaterPlanMapper.selectWorkflowWaterPlanList(workflowWaterPlan);
        List<WorkflowWaterPlan> resworkflowWaterPlans = new ArrayList<>();
        if (workflowWaterPlans != null && !workflowWaterPlans.isEmpty()) {
            /**
             * 单位信息
             */
            List<BtSwUnit> unitList = btSwUnitService.selectBtSwUnitList(new BtSwUnit());
            Map<Long, BtSwUnit> unitMap = new HashMap<>();
            if (unitList != null && !unitList.isEmpty()) {
                unitMap = unitList.stream().collect(Collectors.toMap(BtSwUnit::getId, a -> a, (k1, k2) -> k1));
            }

            /**
             * 机构信息
             */
            List<SysDept> sysDeptList = sysDeptService.selectDeptList(new SysDept());
            Map<Long, SysDept> deptMap = new HashMap<>();
            if (sysDeptList != null && !sysDeptList.isEmpty()) {
                deptMap = sysDeptList.stream().collect(Collectors.toMap(SysDept::getDeptId, a -> a, (k1, k2) -> k1));
            }

            /**
             * 用水计划年度
             */
            List<SwWaterPlanMonthly> monthlyList = swWaterPlanMonthlyService.statisticalWaterType();
            Map<Long, List<SwWaterPlanMonthly>> planMonthlyMap = new HashMap<>();
            if (monthlyList != null && !monthlyList.isEmpty()) {
                planMonthlyMap = monthlyList.stream().collect(Collectors.groupingBy(SwWaterPlanMonthly::getPlanId));
            }
            for (WorkflowWaterPlan plan : workflowWaterPlans) {
                Long deptId = SecurityUtils.getLoginUser().getUser().getDeptId();
                if(deptId == 100 || deptId == 103 || deptId == 105){
                    if(103 == deptId){
                        if("0".equals(plan.getType())){
                            continue;
                        }
                    }
                    if(105 == deptId){
                        if("1".equals(plan.getType())){
                            continue;
                        }
                    }
                }
                plan.setFillingDate(plan.getCreateTime()); // 填报时间
                if(CommonResult.PLAN_TYPE.INDUSTRY.getValue().equals(plan.getType())){
                    // 用水单位
                    BtSwUnit swUnit = unitMap.get(plan.getUnitId());
                    if (swUnit != null) {
                        plan.setUnitCode(swUnit.getUnitCode()); // 单位代码
                        plan.setUnitName(swUnit.getUnitName()); // 单位名称
                        plan.setContacts(swUnit.getContacts()); // 联系人
                        plan.setTel(swUnit.getTel()); // 联系方式
                    }
                }else {
                    SysDept sysDept = deptMap.get(plan.getDeptId());
                    if (sysDept != null) {
                        plan.setUnitName(sysDept.getDeptName()); // 机构名称
                        plan.setContacts(sysDept.getLeader()); // 联系人
                        plan.setTel(sysDept.getPhone()); // 联系方式
                    }
                }

                List<SwWaterPlanMonthly> planMonthlyList = planMonthlyMap.get(plan.getPlanId());
                if (planMonthlyList != null && !planMonthlyList.isEmpty()) {
                    // 总量
                    Double total = 0D;
                    // 城市公共供水
                    Double urbanWaterSupply = 0D;
                    // 地表水
                    Double surfaceWater = 0D;
                    // 地下水
                    Double groundwater = 0D;
                    for (SwWaterPlanMonthly planMonthly : planMonthlyList) {
                        if (null != planMonthly.getReportWaterNum()) {
                            total = Arith.add(total, planMonthly.getReportWaterNum());
                            if (CommonResult.WATER_TYPE.URBAN_PUBLIC_WATER_SUPPLY.getValue().equals(planMonthly.getWaterType())) {
                                urbanWaterSupply = planMonthly.getReportWaterNum();
                            }
                            if (CommonResult.WATER_TYPE.SURFACE_WATER.getValue().equals(planMonthly.getWaterType())) {
                                surfaceWater = planMonthly.getReportWaterNum();
                            }
                            if (CommonResult.WATER_TYPE.GROUNDWATER.getValue().equals(planMonthly.getWaterType())) {
                                groundwater = planMonthly.getReportWaterNum();
                            }
                        }
                    }
                    plan.setTotal(total);
                    plan.setUrbanWaterSupply(urbanWaterSupply);
                    plan.setSurfaceWater(surfaceWater);
                    plan.setGroundwater(groundwater);
                    //
                    List<String> userRoles = SecurityUtils.getLoginUser().getUser().getRoles().stream().map(SysRole::getRoleKey).collect(Collectors.toList());
//                    String currentUserRole;
//                    try {
//                        currentUserRole = userRoles.stream().filter(item -> WorkFlowConstants.WATER_PLAN_ROLE_GROUP.getRoleGroupEnum(item) != null).findAny().get();
//                    } catch (Exception e) {
//                        throw new ServiceException("暂无权限查看数据");
//                    }
//
//                    if (!CollUtil.containsAny(StrUtil.split(plan.getRolegroup(), ","), userRoles)) {
//                        throw new ServiceException("暂无权限查看数据");
//                    }

                    String processDefinitionKey = WorkFlowConstants.WATER_PLAN_CHANNEL.getEnum(plan.getChannel(), "year").getName();

                    String waterPlanProcessDefinitionId = workFlowCache.getWaterPlanProcessDefinitionId(plan.getInstanceId(), processDefinitionKey);
                    Collection<FlowElement> waterPlanFlowElementList = workFlowCache.getWaterPlanFlowElementList(waterPlanProcessDefinitionId);
                    int currentUserRoleSeq = 0, dbUserRoleSeq = 0, i = 0;
                    Iterator<FlowElement> iterator = waterPlanFlowElementList.iterator();
                    while (iterator.hasNext()) {
                        i++;
                        FlowElement flowElement = iterator.next();
                        if (flowElement instanceof UserTask) {
                            UserTask userTask = (UserTask) flowElement;
                            if (CollUtil.containsAny(userTask.getCandidateGroups(), userRoles)) {
                                currentUserRoleSeq = i;
                            }
                            if (CollUtil.containsAny(userTask.getCandidateGroups(), StrUtil.split(plan.getRolegroup(), ","))) {
                                dbUserRoleSeq = i;
                            }
                        }
                    }
                    int diffSeq = currentUserRoleSeq - dbUserRoleSeq;
                    // 查询待提交
                    if ("1".equals(workflowWaterPlan.getReviewStatus()) && diffSeq == 0 && !"9".equals(plan.getState())) {
                        plan.setStatus("1");
                        resworkflowWaterPlans.add(plan);
                    } else if ("2".equals(workflowWaterPlan.getReviewStatus())) {
                        if ("9".equals(plan.getState())) {
                            plan.setStatus("2");
                        } else {
                            if (diffSeq <= -1) {
                                plan.setStatus("2");
                            } else {
                                continue;
                            }
                        }
                        resworkflowWaterPlans.add(plan);
                    } else if ("3".equals(workflowWaterPlan.getReviewStatus()) ) {
                        if("9".equals(plan.getState())){
                            plan.setStatus("2");
                        } else {
                            if (diffSeq == 0) {
                                plan.setStatus("1");
                            } else if (diffSeq <= -1) {
                                plan.setStatus("2");
                            } else {
                                continue;
                            }
                        }
                        resworkflowWaterPlans.add(plan);
                    }
                }
            }
        }
        return resworkflowWaterPlans;
    }


    /**
     * 新增用水申请
     *
     * @param workflowWaterPlan 用水申请
     * @return 结果
     */
    @Override
    public int insertWorkflowWaterPlan(WorkflowWaterPlan workflowWaterPlan) {
        String id = UUID.randomUUID().toString();
        workflowWaterPlan.setId(id);
        workflowWaterPlan.setCreateTime(DateUtils.getNowDate());
        ProcessInstance processInstance = startProcess(workflowWaterPlan);
        List<String> userRoles = SecurityUtils.getLoginUser().getUser().getRoles().stream().map(SysRole::getRoleKey).collect(Collectors.toList());
        Task firstUserTask = taskService.createTaskQuery().processInstanceId(processInstance.getId())
                .taskCandidateGroupIn(userRoles).singleResult();
        taskService.claim(firstUserTask.getId(), SecurityUtils.getLoginUser().getUsername());
        taskService.setAssignee(firstUserTask.getId(), SecurityUtils.getLoginUser().getUsername());
        taskService.setVariableLocal(firstUserTask.getId(), "userName", SecurityUtils.getLoginUser().getUsername());
        taskService.setVariableLocal(firstUserTask.getId(), "depId", SecurityUtils.getLoginUser().getUser().getDeptId());
        taskService.complete(firstUserTask.getId());
        Map<String, UserTask> userTaskList = workFlowCache.getUserTaskList(processInstance.getProcessDefinitionId());
        workflowWaterPlan.setRolegroup(userTaskList.get(firstUserTask.getTaskDefinitionKey()).getFormKey().split("#")[1]);
        workflowWaterPlan.setInstanceId(processInstance.getId());
        workflowWaterPlan.setState(WorkFlowConstants.WATER_PLAN_STATUS_ENUM.INIT.getValue());
        workflowWaterPlan.setCreateName(SecurityUtils.getNickName());
        workflowWaterPlan.setCreateBy(SecurityUtils.getUsername());
        workflowWaterPlan.setCreateTime(DateUtils.getNowDate());
        return workflowWaterPlanMapper.insertWorkflowWaterPlan(workflowWaterPlan);
    }

    private ProcessInstance startProcess(WorkflowWaterPlan workflowWaterPlan) {
        Map<String, Object> processVariableMap = new HashMap<>();
        processVariableMap.put("planId", workflowWaterPlan.getPlanId());
        processVariableMap.put("workflowWaterPlanId", workflowWaterPlan.getId());
        processVariableMap.put("channel", workflowWaterPlan.getChannel());
        processVariableMap.put("startDepId", SecurityUtils.getLoginUser().getUser().getDeptId());
        String processDefinitionKey = WorkFlowConstants.WATER_PLAN_CHANNEL.getEnum(workflowWaterPlan.getChannel(), "year").getName();
        processVariableMap.put("key", processDefinitionKey);
        ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder
                .start()
                .withProcessDefinitionKey(processDefinitionKey)
                .withBusinessKey(workflowWaterPlan.getId())
                .withVariables(processVariableMap)
                .withName(Objects.requireNonNull(WorkFlowConstants.WATER_PLAN_CHANNEL.getEnum(workflowWaterPlan.getChannel(), "year")).getLabel())
                .build());
        return processInstance;
    }

    /**
     * 修改用水申请
     *
     * @param workflowWaterPlan 用水申请
     * @return 结果
     */
    @Override
    public int updateWorkflowWaterPlan(WorkflowWaterPlan workflowWaterPlan) {
        workflowWaterPlan.setUpdateTime(DateUtils.getNowDate());
        return workflowWaterPlanMapper.updateWorkflowWaterPlan(workflowWaterPlan);
    }

    /**
     * 批量删除用水申请
     *
     * @param ids 需要删除的用水申请ID
     * @return 结果
     */
    @Override
    public int deleteWorkflowWaterPlanByIds(String[] ids) {
        return workflowWaterPlanMapper.deleteWorkflowWaterPlanByIds(ids);
    }

    /**
     * 删除用水申请信息
     *
     * @param id 用水申请ID
     * @return 结果
     */
    @Override
    public int deleteWorkflowWaterPlanById(String id) {
        return workflowWaterPlanMapper.deleteWorkflowWaterPlanById(id);
    }

    /**
     * 提交审批
     *
     * @param plan
     * @return
     */
    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public int updatePlanSP(Plan plan) {
        SwWaterPlan swWaterPlan = waterPlanService.selectSwWaterPlanById(plan.getId());
        if (null == swWaterPlan) {
            return 0;
        } else {
            if (ZERO.equals(swWaterPlan.getStatus()) || NO_PASS.getValue().equals(swWaterPlan.getStatus())) {

                if(ZERO.equals(swWaterPlan.getStatus())){
                    WorkflowWaterPlan workflowWaterPlan = new WorkflowWaterPlan();
                    // 计划Id
                    workflowWaterPlan.setPlanId(swWaterPlan.getId());
                    workflowWaterPlan.setDeptId(swWaterPlan.getDeptId());
                    // 申请渠道 1：农业  2：非农
                    if("0".equals(swWaterPlan.getType())){
                        workflowWaterPlan.setChannel("2");
                    } else {
                        workflowWaterPlan.setChannel("1");
                    }
                    this.insertWorkflowWaterPlan(workflowWaterPlan);
                    swWaterPlan.setStatus(BESUBMITTED.getValue());
                    int i = waterPlanService.updateSwWaterPlanDto(swWaterPlan);

                    // 开始节点提交历史信息
                    BtFlowHistory btFlowHistory = new BtFlowHistory();
                    btFlowHistory.setcDate(new Date());
                    SysUser user = SecurityUtils.getLoginUser().getUser();
                    btFlowHistory.setUserId(user.getUserId());
                    btFlowHistory.setUserName(user.getNickName());
                    btFlowHistory.setReason(plan.getReason());
                    btFlowHistory.setServiceId(swWaterPlan.getId());
                    btFlowHistoryService.insertBtFlowHistory(btFlowHistory);
                    return i;

                } else {
                    swWaterPlan.setStatus(BESUBMITTED.getValue());
                    int i = waterPlanService.updateSwWaterPlanDto(swWaterPlan);
                    // 重复提交
                    this.completeTaskByPlanID(swWaterPlan.getId());
                    return i;
                }
            } else {
                return 2;
            }
        }
    }

    /**
     * 拾取任务
     *
     * @param workflowWaterPlan
     */
    @Override
    public void claimTask(WorkflowWaterPlan workflowWaterPlan) {
        List<String> roles = StrUtil.split(workflowWaterPlan.getRolegroup(), ",");
        Task task = taskService.createTaskQuery().taskCandidateGroupIn(roles).processInstanceId(workflowWaterPlan.getInstanceId()).singleResult();
        String username = SecurityUtils.getUsername();
        if (Objects.isNull(task)) {
            log.info("{}没找到可以拾取的任务", username);
        }
        taskService.claim(task.getId(), username);
        workflowWaterPlan.setAssignee(username);
        workflowWaterPlan.setState(WorkFlowConstants.WATER_PLAN_STATUS_ENUM.WAIT_CHECK.getValue());
        workflowWaterPlan.setUpdateTime(new Date());
        workflowWaterPlan.setUpdateBy(username);
        workflowWaterPlanMapper.updateWorkflowWaterPlan(workflowWaterPlan);

    }

    /**
     * 归还任务,交给其他人处理
     *
     * @param workflowWaterPlan
     */
    @Override
    public void unClaimTask(WorkflowWaterPlan workflowWaterPlan) {
        List<String> roles = StrUtil.split(workflowWaterPlan.getRolegroup(), ",");
        String username = SecurityUtils.getUsername();
        Task task = taskService.createTaskQuery().taskCandidateGroupIn(roles).processInstanceId(workflowWaterPlan.getInstanceId()).singleResult();
        if (Objects.isNull(task)) {
            log.info("{}没找到可以归还的任务", username);
            return;
        }
        taskService.unclaim(task.getId());
        workflowWaterPlan.setAssignee(null);
        workflowWaterPlan.setState(WorkFlowConstants.WATER_PLAN_STATUS_ENUM.WAIT_CHECK.getValue());
        workflowWaterPlan.setUpdateTime(new Date());
        workflowWaterPlan.setUpdateBy(username);
        workflowWaterPlanMapper.updateWorkflowWaterPlan(workflowWaterPlan);
    }

    /**
     * 通过任务
     *
     * @param workflowWaterPlan
     */
    @Override
    public void completeTask(WorkflowWaterPlan workflowWaterPlan) {
        String username = SecurityUtils.getUsername();
        Task task = taskService.createTaskQuery().taskAssignee(username).processInstanceId(workflowWaterPlan.getInstanceId()).singleResult();
        if (Objects.isNull(task)) {
            log.info("{}没找到可以通过的任务", username);
        }
        taskService.setVariableLocal(task.getId(), "userName", SecurityUtils.getLoginUser().getUsername());
        taskService.setVariableLocal(task.getId(), "depId", SecurityUtils.getLoginUser().getUser().getDeptId());
        taskService.complete(task.getId());
        workflowWaterPlan.setAssignee(null);

        List<String> formKeyStrList = StrUtil.split(task.getFormKey(), "#");
        String nextRoleGroup = formKeyStrList.get(1);
        if (StringUtils.isEmpty(nextRoleGroup)) {
            workflowWaterPlan.setState(WorkFlowConstants.WATER_PLAN_STATUS_ENUM.FINISH.getValue());
        }
        workflowWaterPlan.setActivitiname(task.getName());
        workflowWaterPlan.setRolegroup(nextRoleGroup);
        workflowWaterPlan.setUpdateTime(new Date());
        workflowWaterPlan.setUpdateBy(username);
        workflowWaterPlanMapper.updateWorkflowWaterPlan(workflowWaterPlan);
    }

    @Override
    public void rejectTask(WorkflowWaterPlan workflowWaterPlan) {
        String username = SecurityUtils.getUsername();
        List<String> roles = StrUtil.split(workflowWaterPlan.getRolegroup(), ",");
        Task task = taskService.createTaskQuery().taskCandidateGroupIn(roles).processInstanceId(workflowWaterPlan.getInstanceId()).singleResult();
        if (Objects.isNull(task)) {
            log.info("{}没找到可以拒绝的任务", username);
            throw new CustomException(username + "没找到可以拾取的任务");
        }
        List<String> formKeyStrList = StrUtil.split(task.getFormKey(), "#");
        String fromAcitivitiId = task.getTaskDefinitionKey(),
                toActivitiId = formKeyStrList.get(2);
        taskService.setVariableLocal(task.getId(), "userName", SecurityUtils.getLoginUser().getUsername());
        taskService.setVariableLocal(task.getId(), "depId", SecurityUtils.getLoginUser().getUser().getDeptId());
        dynamicJumpService.execution(workflowWaterPlan.getInstanceId(), fromAcitivitiId, toActivitiId);
        workflowWaterPlan.setAssignee(null);
        String backRoleGroup = formKeyStrList.get(0);
        if (StringUtils.isNotEmpty(backRoleGroup)) {
            workflowWaterPlan.setRolegroup(backRoleGroup);
        }
        workflowWaterPlan.setRolegroup(backRoleGroup);
        workflowWaterPlan.setState(WorkFlowConstants.WATER_PLAN_STATUS_ENUM.REJECT.getValue());
        workflowWaterPlan.setUpdateTime(new Date());
        workflowWaterPlan.setUpdateBy(username);
        workflowWaterPlanMapper.updateWorkflowWaterPlan(workflowWaterPlan);
    }

    @Override
    public int completeTaskByPlanID(Long planId) {
        WorkflowWaterPlan workflowWaterPlan = new WorkflowWaterPlan();
        workflowWaterPlan.setPlanId(planId);
        List<WorkflowWaterPlan> workflowWaterPlans = workflowWaterPlanMapper.selectWorkflowWaterPlanList(workflowWaterPlan);
        if (CollectionUtil.isEmpty(workflowWaterPlans)) {
            throw new CustomException("没找到可以审核的任务");
        }
        workflowWaterPlan = workflowWaterPlans.get(0);
        if (WorkFlowConstants.WATER_PLAN_STATUS_ENUM.FINISH.getValue().equals(workflowWaterPlan.getState())) {
            throw new CustomException("已经结束的任务不可以审核");
        }
        claimTask(workflowWaterPlan);
        completeTask(workflowWaterPlan);

        // 通过
        BtFlowHistory btFlowHistory = new BtFlowHistory();
        btFlowHistory.setcDate(new Date());
        SysUser user = SecurityUtils.getLoginUser().getUser();
        btFlowHistory.setUserId(user.getUserId());
        btFlowHistory.setUserName(user.getNickName());
        btFlowHistory.setStatus("1");
        btFlowHistory.setReason("通过");
        btFlowHistory.setServiceId(planId);
        btFlowHistoryService.insertBtFlowHistory(btFlowHistory);

        return 1;
}

    @Override
    public int rejectTaskByPlanID(Plan plan) {
        WorkflowWaterPlan workflowWaterPlan = new WorkflowWaterPlan();
        workflowWaterPlan.setPlanId(plan.getId());
        List<WorkflowWaterPlan> workflowWaterPlans = workflowWaterPlanMapper.selectWorkflowWaterPlanList(workflowWaterPlan);
        if (CollectionUtil.isEmpty(workflowWaterPlans)) {
            throw new CustomException("没找到可以拒绝的任务");
        }
        workflowWaterPlan = workflowWaterPlans.get(0);
        if (WorkFlowConstants.WATER_PLAN_STATUS_ENUM.FINISH.getValue().equals(workflowWaterPlan.getStatus())) {
            throw new CustomException("已经结束的任务不可以驳回");
        }
        unClaimTask(workflowWaterPlan);
        rejectTask(workflowWaterPlan);
        // 开始节点提交历史信息
        BtFlowHistory btFlowHistory = new BtFlowHistory();
        btFlowHistory.setcDate(new Date());
        SysUser user = SecurityUtils.getLoginUser().getUser();
        btFlowHistory.setUserId(user.getUserId());
        btFlowHistory.setUserName(user.getNickName());
        btFlowHistory.setReason(plan.getReason());
        btFlowHistory.setStatus("2");
        btFlowHistory.setServiceId(plan.getId());
        btFlowHistoryService.insertBtFlowHistory(btFlowHistory);
        return 1;
    }

    /**
     * 审批
     *
     * @param plan
     * @return
     */
    @Override
    public int examinePlan(Plan plan) {
        int index = 0;
        /**
         * 用水计划产品明细对象
         */
        List<PlanDetail> planDetailList = plan.getPlanDetailList();
        if(planDetailList != null && !planDetailList.isEmpty()){
            /**
             * 定额信息
             */
            List<BsSwQuotaIndustry> quotaList = swQuotaIndustryService.selectBsSwQuotaIndustryList(new BsSwQuotaIndustry());
            Map<Long, BsSwQuotaIndustry> quotaMap = new HashMap<>();
            if(quotaList != null && !quotaList.isEmpty()){
                quotaMap = quotaList.stream().collect(Collectors.toMap(BsSwQuotaIndustry::getId, a -> a, (k1, k2) -> k1));
            }
            // 计划年取水量
            double planWater = 0D;
            for(PlanDetail planDetail : planDetailList){
                BsSwQuotaIndustry industry = quotaMap.get(planDetail.getQuotaId());
                double ratio  = 1D;
                // 先判断是否存在等效配置系数
                if(null != industry.getMaxRatio() && null != industry.getMinRatio()){
                    if((planDetail.getRatio().compareTo(industry.getMaxRatio()) < 0
                            && planDetail.getRatio().compareTo(industry.getMinRatio()) > 0)
                            || planDetail.getRatio().compareTo(industry.getMaxRatio()) == 0
                            || planDetail.getRatio().compareTo(industry.getMinRatio()) == 0){
                        ratio =  planDetail.getRatio();
                    }else {
                        throw new ServiceException("行业代码为"+planDetail.getIndustryCode()+"审批系数不在设置系数的范围");
                    }
                }
                Double quota = Arith.div(planDetail.getExamineWaterConsumption(), planDetail.getExamineNum());
                // 调整的定额 （定额 * 调整系数）
                Double waterQuota = Arith.mul(ratio,planDetail.getWaterQuota());
                if(quota.compareTo(waterQuota) < 0
                        || quota.compareTo(waterQuota) == 0){
                    planWater = Arith.add(planWater,planDetail.getExamineWaterConsumption());
                }else {
                    throw new ServiceException("行业代码为"+planDetail.getSubType()+"审批用水量大于设置定额");
                }
            }
            Double sumPlanMonthly = swWaterPlanMonthlyService.sumPlanMonthly(plan.getPlanNonfarmMonthlyList());
            Double sumPlanAnnual = swWaterPlanAnnualService.sumPlanAnnual(plan.getPlanNonfarmAnnualList());
//            if(sumPlanMonthly.compareTo(sumPlanAnnual) != 0){
//                throw new ServiceException("月度用水计划总量和年度用水计划总量不相等！");
//            }
            SwWaterPlan swWaterPlan = new SwWaterPlan();
            BeanUtils.copyProperties(plan,swWaterPlan);
            swWaterPlan.setApproveWater(planWater);
            index = swWaterPlanService.updateSwWaterPlanDto(swWaterPlan);
            for(PlanDetail planDetail : planDetailList){
                SwWaterPlanDetail swWaterPlanDetail = new SwWaterPlanDetail();
                BeanUtils.copyProperties(planDetail,swWaterPlanDetail);
                swWaterPlanDetailService.updateSwWaterPlanDetail(swWaterPlanDetail);
            }
            /**
             * 月份计划
             */
            List<PlanNonfarmMonthly> planNonfarmMonthlyList = plan.getPlanNonfarmMonthlyList();
            if(planNonfarmMonthlyList != null && !planNonfarmMonthlyList.isEmpty()){
                swWaterPlanMonthlyService.examinePlanMonthly(planNonfarmMonthlyList,swWaterPlan.getId());
            }
            /**
             * 年度计划
             */
            List<PlanNonfarmAnnual> planNonfarmAnnualList = plan.getPlanNonfarmAnnualList();
            if(planNonfarmAnnualList != null && !planNonfarmAnnualList.isEmpty()){
                swWaterPlanAnnualService.examinePlanAnnual(planNonfarmAnnualList,swWaterPlan.getId());
            }
        }
        return index;
    }


    /**
     * 审批(农业)
     *
     * @param plan
     * @return
     */
    @Override
    public int examineAgriculturePlan(Plan plan) {
        int index = 0;
        /**
         * 用水计划产品明细对象
         */
        List<SwWaterPlanAgricultureDetail> planDetailList = plan.getPlanAgricultureDetailList();
        if(planDetailList != null && !planDetailList.isEmpty()){
            // 计划年取水量
            double planWater = 0D;
            for(SwWaterPlanAgricultureDetail planDetail : planDetailList){
                Double quota = 0D;
                // 理论用水量
                quota = Arith.div(Arith.mul(planDetail.getExamineArea(), planDetail.getExamineWater50()),plan.getCoefficient(),5);
                // 实际用水量
                Double waterConsumption = Arith.add(planDetail.getExamineSurfaceWater(), Arith.add(planDetail.getExamineGroundWater(),planDetail.getExamineUnconventionalWater()));
                if(quota.compareTo(waterConsumption) > 0
                        || quota.compareTo(waterConsumption) == 0){
                    planWater = Arith.add(planWater,quota);
                }else {
                    throw new ServiceException("作物为"+planDetail.getCropName()+"上报用水量大于设置定额");
                }
            }
            SwWaterPlan swWaterPlan = new SwWaterPlan();
            BeanUtils.copyProperties(plan,swWaterPlan);
            swWaterPlan.setApproveWater(planWater);
            index = swWaterPlanService.updateSwWaterPlanDto(swWaterPlan);
            for(SwWaterPlanAgricultureDetail planDetail : planDetailList){
                SwWaterPlanAgricultureDetail swWaterPlanAgricultureDetail = new SwWaterPlanAgricultureDetail();
                BeanUtils.copyProperties(planDetail,swWaterPlanAgricultureDetail);
                swWaterPlanAgricultureDetailService.updateSwWaterPlanAgricultureDetail(swWaterPlanAgricultureDetail);
            }
            /**
             * 月份计划
             */
            List<PlanNonfarmMonthly> planNonfarmMonthlyList = plan.getPlanNonfarmMonthlyList();
            if(planNonfarmMonthlyList != null && !planNonfarmMonthlyList.isEmpty()){
                swWaterPlanMonthlyService.examineAgriculturePlanMonthly(planNonfarmMonthlyList,swWaterPlan.getId());
            }
            /**
             * 年度计划
             */
            List<PlanAgricultureAnnual> planAgricultureAnnualList = plan.getPlanAgricultureAnnualList();
            if(planAgricultureAnnualList != null && !planAgricultureAnnualList.isEmpty()){
                swWaterPlanAnnualService.examineAgriculturePlanAnnual(planAgricultureAnnualList,swWaterPlan.getId());
            }
        }
        return index;
    }
}
